<?php
namespace api\modules\v1\models\shop;

use api\modules\v1\models\Common;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * Class UserActiveRecord
 * @package api\modules\v1\models
 */
class GoodsOrderDetail extends \common\models\shop\GoodsOrderDetail
{

    /**
     * 商品规格订单
     * @param int $userId
     * @param string $orderNumber
     * @param int $detailId
     * @param int $buyNum
     * @param array $goodsDetail
     * @return mixed
     * @throws Exception
     */
    public function createOrderDetail($userId = 0, $orderNumber = '', $buyNum = 0, $detailId = 0, $goodsDetail = []) {
        $userId = (int) $userId;
        if (empty($userId)) {
            throw new Exception('未知用户');
        }

        if (empty($orderNumber)) {
            throw new Exception('未知订单');
        }
        $detailId = (int) $detailId;
        if (empty($detailId)) {
            throw new Exception('未知数据');
        }
        $buyNum = (int) $buyNum;
        if (empty($buyNum) || $buyNum <= 0) {
            throw new Exception('数量不能为空');
        }
        $detailInfo = $goodsDetail;
        $goodsInfo = ArrayHelper::getValue($detailInfo,'goods',[]);
        if (empty($detailInfo) || empty($goodsInfo)) {
            throw new Exception('商品信息错误');
        }
        $data['order_number'] = $orderNumber;
        $data['goods_id'] = $detailInfo['goods_id'];
        $data['goods_detail_id'] = $detailId;
        $data['goods_price'] = (double) $detailInfo['goods_price'];
        $data['buy_num'] = $buyNum;
        $data['goods_name'] = $goodsInfo['name'];
        $data['create_time'] = date("Y-m-d H:i:s");

        $result['total_money'] = $data['goods_price'] * $buyNum;
        $result['goods_name'] = $goodsInfo['name'];
        $result['spec_name'] = $detailInfo['goods_spec'];
        $result['num'] = $buyNum;

        $res = static::insertData($data);

        if ($res === false) {
            throw new Exception('系统错误');
        }

        return $result;
    }
}
